<template>
  <div>
    <van-nav-bar v-if="showNavBar" :title="title" :left-arrow="back" @click-left="onClickBack"/>
    <slot :contentClass="{'content-height-has-nav': showNavBar, 'pt-4': true}" :listerData="listerData"></slot>
  </div>
</template>

<script setup>
import {useRouter, useRoute} from "vue-router";
import {computed, onMounted, watch, ref, inject} from "vue";
import {useStore} from "vuex";

const props = defineProps({
  "showNavBar": {
    type: Boolean,
    default: () => true
  },
  "title": {
    type: String,
    default: () => ""
  },
  "back": {
    type: Boolean,
    default: () => true
  },
  "lister": {
    type: Object,
    default: () => ({
      "enabled": false,
      "pageable": {
        type: Boolean,
        default: () => false
      },
      "modelName": {
        type: String,
        default: () => null
      },
      "query": {
        type: Object,
        default: () => {}
      }
    })
  },
})

const router = useRouter()
const route = useRoute()
const store = useStore()

const title = computed(() => props.title || route.meta.title)


import apis from '../apis'

/* List data */
const lister = ref(props.lister.pageable ? {page: 1, size: 10, total: 0, data: []} : [])

const hasMore = computed(() => props.lister.pageable ? lister.value.page * lister.value.size < lister.value.total : false)

const listerData = computed(() => props.lister.pageable ? lister.value.data : lister.value)

if (props.lister.enabled) {

  const pageAfter = inject('pageAfter')

  const refresh = () => {
    const config = {
      label: props.lister.modelName + '_list',
      show_loading: true
    }

    if (props.lister.pageable) {
      config.params = {
        page: lister.value.page,
        size: lister.value.size,
        ...props.lister.query
      }
    }

    let modelName = props.lister.modelName
    let methodName = 'lister'
    if (props.lister.modelName.indexOf('.') != "-1") {
      modelName = props.lister.modelName.split('.')[0]
      methodName = props.lister.modelName.split('.')[1]
    }
    apis[modelName][methodName](config).then((response) => {
      const result = response.data
      const page = result.data
      pageAfter && pageAfter(page)
      lister.value = page
    })
  }

  watch(() => lister.value.page, value => {
    refresh()
  })

  refresh()

}

const nextPage = () => {
  lister.value.page = lister.value.page + 1
}

defineExpose({
  lister,
  nextPage,
  hasMore,
})

onMounted(() => {

})

/* Back */
const onClickBack = () => {
  router.back()
}
</script>

<style scoped>

</style>
